<template>
    <a-modal v-model="visible" @cancel="handelCancel" :title="title" destroyOnClose :maskClosable="false" width="960px">
      <template slot="footer">
        <a-button @click="handelPrev">{{ current > 0 ? "上一步" : "取消" }}</a-button>
        <a-button key="back" type="primary" @click="handleNext" v-if="current < 1">下一步</a-button>
        <a-button key="submit" type="primary" @click="handleOk" v-else>提交订单</a-button>
      </template>
      <a-steps :current="current">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <div class="steps-content" v-if="current === 0">
        <a-button class="editable-add-btn" @click="handleAddProduct">添加耗材</a-button>
        <a-table :columns="columns" rowKey="key" :data-source="orderDetailList" bordered>
          <template slot="productName" slot-scope="text, record">
            <a-auto-complete style="width: 100%" placeholder="输入关键字模糊搜索" @search="handleSearchProduct" @select="e => handleSelectProduct(e,record.key)">
              <template slot="dataSource">
                <a-select-option v-for="product in productList" :key="product.productCode" >
                  {{ product.productName + "（" + product.model + "）" + "【" + product.factory +"】"  }}
                </a-select-option>
              </template>
            </a-auto-complete>
          </template>
          <template slot="quantity" slot-scope="text, record" >
            <a-input-number style="margin: -5px 0" :value="text" @change="onCellChange(record.key, 'quantity', $event)" />
          </template>
          <template slot="productPic" slot-scope="text, record" >
            <a-avatar shape="square" :size="72" :src="record.productPic" icon="file-image" />
          </template>
          <template slot="inventoryStatus" slot-scope="text, record" >
            {{ record.inventoryStatus == 0 ? "库存充足" : record.inventoryStatus == 1 ? "库存紧张" : record.inventoryStatus == 1 ? "库存不足" : "未知" }}
          </template>
          <template slot="operation" slot-scope="text, record">
            <div class="editable-row-operations">
              <a-popconfirm title="是否移除该耗材信息?" @confirm="() => handleDeleteProduct(record.key)">
                <a>删除</a>
              </a-popconfirm>
            </div>
          </template>
        </a-table>
      </div>
      <div class="steps-content" v-if="current === 1">
        <a-form-model :model="order" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="orderRules" ref="orderForm">
          <a-form-model-item label="配送地址">
            <a-select size="large" placeholder="请选择配送地址" label-in-value @select="handleChange">
              <a-select-option v-for="address in addressList" :key="address.id">
                {{address.name}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="患者信息">
            <a-select size="large" placeholder="请选择患者信息" label-in-value @select="handlePatientChange">
              <a-select-option v-for="patient in patientList" :key="patient.code">
                {{patient.name}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="备注">
            <a-input  type="textarea" v-model="order.name" placeholder="请输入备注" />
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
  </template>
  <script>
  export default {
    name: "PlaceOrderForm",
    props: {
      visibleModal: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        title: "创建订单",
        visible: false,
        columns: [
          { title: '商品名称', dataIndex: 'productName', scopedSlots: { customRender: 'productName' } },
          { title: '商品图片', dataIndex: 'productPic', scopedSlots: { customRender: 'productPic' } },
          { title: '规格', dataIndex: 'model' },
          { title: '厂家', dataIndex: 'factory' },
          { title: '库存状态', dataIndex: 'inventoryStatus', scopedSlots: { customRender: 'inventoryStatus' } },
          { title: '数量', dataIndex: 'quantity', scopedSlots: { customRender: 'quantity' } },
          { title: '操作', dataIndex: 'operation', scopedSlots: { customRender: 'operation' } },
        ],
        order: { },
        orderRules: {
          deliveryAddressId: [{ required: true, message: '请选择配送地址！', trigger: 'change' }],
          patientName: [{ required: true, message: '请选择患者信息！', trigger: 'change' }],
        },
        count: 1,
        orderDetailList: [],
        productList: [],
        addressList: [],
        patientList: [],
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
        selectOptions: this.selectOptionDatas,
        current: 0,
        steps: [{ title: "选择耗材" }, { title: "订单确认" }],
      };
    },
    watch: {
      visibleModal: function (val) {
        this.visible = val;
        this.current = 0;
        this.orderDetailList = [];
        this.order = {}
      },
    },
    created(){
      this.queryAddressList();
    },
    methods: {
      queryAddressList(){
        this.$store
        .dispatch("address/querySelect")
        .then((res) => {
          this.addressList = res.data;
        });
      },
      queryPatientList(addressId){
        this.$store
        .dispatch("patient/queryList", { addressId })
        .then((res) => {
          this.patientList = res;
        });
      },
      handleAddProduct(){
        const { count, orderDetailList } = this;
        const product = {
          key: count,
          quantity: 0,
        };
        this.orderDetailList = [...orderDetailList, product];
        this.count = count + 1;
      },
      handleDeleteProduct(key){
        const orderDetailList = [...this.orderDetailList];
        this.orderDetailList = orderDetailList.filter(item => item.key !== key);
      },
      handleSearchProduct(value){
        this.$store
        .dispatch("product/queryList", {limit: 10, page: 0,keyword: value})
        .then((res) => {
          this.productList = res.list;
        });
      },
      handleSelectProduct(productCode,key){
        const productList = [...this.productList];
        var product = productList.find(item=>item.productCode === productCode)

        const orderDetailList = [...this.orderDetailList];
        var isExist =  orderDetailList.some(item => item.productCode === productCode);
        if(!isExist){
          var target = orderDetailList.find(item => item.key === key);
          if (target) {
            target = Object.assign(target,product);
            target.quantity = 1;
            target.productId = product.id
            delete target.id
            this.orderDetailList = orderDetailList;
          }
        } else {
          this.$message.error("耗材信息重复添加")
        }
      },
      onCellChange(key, dataIndex, value) {
        const dataSource = [...this.orderDetailList];
        const target = dataSource.find(item => item.key === key);
        if (target) {
          target[dataIndex] = value;
          this.orderDetailList = dataSource;
        }
      },
      handleChange(value){
        var data = {
          deliveryAddress: value.label,  
          deliveryAddressId: value.key
        }
        const { order } = this;
        this.order = Object.assign(order,data);
        this.queryPatientList(value.key)
      },
      handlePatientChange(value){
        var data = {
          patientName: value.label,  
          patientCode: value.key
        }
        const { order } = this;
        this.order = Object.assign(order,data);
      },
      handleNext() {
        const orderDetailList = [...this.orderDetailList];
        if(orderDetailList.filter(item => item.productCode !== undefined).length > 0) {
          this.current++;
        } else {
          this.$message.error("请添加耗材信息")
        }
      },
      handelPrev() {
        if (this.current > 0) {
          this.current--;
        } else {
          this.current = 0;
          this.visible = false;
          this.$emit("close");
        }
      },
      handelCancel() {
        this.visible = false;
        this.$emit("close");
      },
      handleOk() {
        const orderDetailList = [...this.orderDetailList];
        const { order } = this;
        
        if(order.deliveryAddressId != undefined && order.deliveryAddress != undefined){
          if(order.patientName != undefined && order.patientCode != undefined) {
            order.orderDetailList = orderDetailList.filter(item => item.productCode !== undefined);
            this.$store
              .dispatch(`order/saveOrder`, order)
              .then((res) => {
                this.$message.success("保存成功！");
                this.visible = false;
                this.$emit("close");
              });
            } else {
              this.$message.error("请先选择患者信息");
            }
        } else {
          this.$message.error("请先选择配送地址");
        }
      },
    },
  };
  </script>
  <style scoped>
  .steps-content {
    margin: 40px auto 0px;
  }

  .editable-add-btn{
    margin-bottom: 8px;
  }
  
  </style>